<template>
    <div class="app-container calendar-list-container"> 
        <!-- 搜索框，对工段信息进行搜索 -->
      <div class="filter-container">
        <el-select 
            v-model="listQuery.workCenter" 
            :style="{ width: inputWid(listQuery.workOrderNo) }"
            @focus="getCenterList" 
            placeholder="请选择工作中心"
            class="ul-item">
            <el-option :value="item" :label="item" v-for="(item,index) in this.centerList" :key="index"/>
        </el-select>
        <el-input
                @keyup.enter.native="getData"
                clearable
                v-model="listQuery.workOrderNo"
                style="margin-right: 15px;margin-top:7px"
                :style="{ width: inputWid(listQuery.workOrderNo) }"
                class="filter-item"
                placeholder="请输入工单单号"
        ></el-input>
        <!-- style="width: 150px;margin-right:15px;margin-top:7px" -->
        <el-input
                @keyup.enter.native="getData"
                clearable
                v-model="listQuery.deviceBarcode"
                style="margin-right: 15px;margin-top:7px"
                :style="{ width: inputWid(listQuery.deviceBarcode) }"
                class="filter-item"
                placeholder="请输入机柜条码"
        ></el-input>
        <el-input
                @keyup.enter.native="getData"
                clearable
                v-model="listQuery.technologyNo"
                style="margin-right: 15px;margin-top:7px"
                :style="{ width: inputWid(listQuery.technologyNo) }"
                class="filter-item"
                placeholder="请输入品号"
        ></el-input>
        <el-input
                @keyup.enter.native="getData"
                clearable
                v-model="listQuery.processOrder"
                style="width: 150px;margin-right:15px;margin-top:7px"
                class="filter-item"
                placeholder="工序编号"
        ></el-input>
        <el-input
                @keyup.enter.native="getData"
                clearable
                v-model="listQuery.processName"
                style="width: 150px;margin-right:15px;margin-top:7px"
                class="filter-item"
                placeholder="工序名称"
        ></el-input>
        <el-select 
            @keyup.enter.native="getData"
            v-model="listQuery.isDelete" 
            placeholder="是否删除"
            class="filter-item"
            style="width: 150px;margin-right:15px;margin-top:7px">
            <el-option
                v-for="(item,index) in optionsIsEnd"
                :key="index"
                :label="item"
                :value="item">
            </el-option>
        </el-select>

        <el-date-picker
          v-model="dateOptions"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          style="margin-right:15px;">
        </el-date-picker>

        <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
        <el-button v-if="userInfo.roleId == 14 || userInfo.roleId == 36" class="filter-item" type="success" v-waves @click="missAudit">过站凭证上传</el-button>
      </div>
      <el-dialog
        title="过站凭证上传"
        :visible.sync="dialogVisible"
        width="25%">
        <el-form :rules="rules" ref="form" :model="form">
          <el-form-item prop="type" label="类型" :label-width="formLabelWidth">
            <el-select style="width: 220px" @change="typeChange" v-model="form.type" placeholder="请选择类型">
              <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
            </el-form-item>
            <el-form-item prop="deviceDarcode" label="条码" :label-width="formLabelWidth">
              <el-input style="width: 220px" v-model="form.deviceDarcode" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item v-if="form.type == 1" prop="testResult" label="结果" :label-width="formLabelWidth">
              <el-select style="width: 220px" v-model="form.testResult" placeholder="请选择结果">
                <el-option v-for="item in testResultList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
          </el-form-item>
          <el-form-item v-if="form.type == 2" prop="value" label="值" :label-width="formLabelWidth">
            <el-input style="width: 220px" v-model="form.value" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item v-if="form.type == 1" prop="siteCode" label="工位" :label-width="formLabelWidth">
            <el-input style="width: 220px" v-model="form.siteCode" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item v-if="form.type == 4" prop="siteCode" label="工序" :label-width="formLabelWidth">
            <el-input style="width: 220px" v-model="form.siteCode" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item v-if="form.type == 4" prop="palletCode" label="栈板条码" :label-width="formLabelWidth">
            <el-input style="width: 220px" v-model="form.palletCode" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </el-dialog>
    <!-- 表单 -->
    <el-table :data="tablelList" 
    v-loading="listLoading" 
    element-loading-text="拼命加载中" 
    stripe border fit 
    highlight-current-row 
    style="width: 100%"
    height="700px">
        <el-table-column label="工作中心" prop="workCenter" align="center"/>
        <el-table-column label="线体" prop="sectionAbbreviation" align="center"/>
        <el-table-column label="客户品号" prop="clientNumber" align="center"/>
        <el-table-column label="工序编号" prop="scanProcessOrder" align="center"/>
        <el-table-column label="工序名称" prop="scanProcessName" align="center"/>
        <el-table-column label="工别" prop="scanOrderType" align="center"/>
        <el-table-column label="工单" prop="scanWorkOrderNo" align="center"/>
        <el-table-column label="机柜条码" prop="deviceBarcode" align="center"/>
        <el-table-column label="SOP号" prop="sopBarcode" align="center"/>
        <el-table-column label="品号" prop="scanProduceNo" align="center"/>
        <el-table-column label="扫码时间" prop="scanTime" align="center"/>
        <el-table-column label="是否删除" prop="isDelete" align="center">
        <template slot-scope="scope">
            <div class="fx">
              {{
                scope.row.isDelete == 0
                  ? "未删除"
                  : "已删除"
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="QC检验状态" prop="checkPassEms" align="center">
        <template slot-scope="scope">
            <div class="fx">
              {{
                scope.row.checkPassEms == 0
                  ? "未检查"
                  : scope.row.checkPassEms == 1
                  ? "合格"
                  : scope.row.checkPassEms == 2
                  ? "不合格":""
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="OBA检验状态" prop="checkPass" align="center">
        <template slot-scope="scope">
            <div class="fx">
              {{
                scope.row.checkPass == 0
                  ? "未检查"
                  : scope.row.checkPass == 1
                  ? "合格"
                  : scope.row.checkPass == 2
                  ? "不合格":""
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="工作人员" prop="userName" align="center"/>
        <el-table-column label="检验人员"  prop="checkJobNumber" align="center"/>
    </el-table>

    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40,100,300,500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>

    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

    </div>
</template>

<script>
import { findDeviceBarcodeCode,sopScanIf } from '../../api/processRoute'
import mixin from '../../utils/mixin.js'
export default {
    name: 'codePassList',
    mixins: [mixin],
    data() {
        return {
          formLabelWidth: '80px',
          typeList:[{name:'智能电批',id:1},{name:'注液凭证',id:2},{name:'按照机柜条码工序替换栈板条码',id:4}],
          testResultList:[{name:'成功',id:'True'},{name:'失败',id:'Flase'}],
          form:{
            type:'',
            deviceDarcode:'',
            testResult:'',
            value:'',
            siteCode:'',
            palletCode:'',
          },
          dialogVisible:false,
            listQuery: {                                //搜索的内容表单
                page: 1,
                limit: 20
            },
            dateOptions: this.getNowTime(),
            pickerOptions: {
              shortcuts: [{
                text: '最近一周',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '最近一个月',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '最近三个月',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                  picker.$emit('pick', [start, end]);
                }
              }]
            },
            total: 0,                                  //总的信息条数
            tablelList: [],                               //table表单的信息                   
            listLoading: false,                          //table加载的动画控制条件
            optionsIsEnd: ['已删除','未删除'],
            userInfo: this.$store.state.user.userInfo,
            rules: {
              type: [
                { required: true, message: '请选择类型', trigger: 'blur' }
              ],
              deviceDarcode: [
                { required: true, message: '请输入条码', trigger: 'blur' }
              ],
              testResult: [
                { required: true, message: '请输入结果', trigger: 'blur' }
              ],
              value: [
                { required: true, message: '请输入值', trigger: 'blur' }
              ],
              siteCode: [
                { required: true, message: '请输入工位', trigger: 'blur' }
              ],
              palletCode: [
                { required: true, message: '请输入栈板条码', trigger: 'blur' }
              ]
            }
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
      // 点击确定
      async submit(){
        await this.$refs.form.validate()
        let query = Object.assign({},this.form)
        if(this.form.type == 1){
          delete query.value
          delete query.palletCode
        }
        if(this.form.type == 2){
          delete query.testResult
          delete query.siteCode
          delete query.palletCode
        }
        if(this.form.type == 4){
          delete query.value
          delete query.testResult
        }
        const res = await sopScanIf(query)
        if(res.code == 1){
          this.$message.success(res.msg)
          this.form = {
            type:'',
            deviceDarcode:'',
            testResult:'',
            value:'',
            siteCode:'',
            palletCode:'',
          }
          this.dialogVisible = false
        } else {
          this.$message.error(res.msg)
        }
        console.log(res);
      },
      // 类型切换
      typeChange(e){
        console.log(e);
      },
      missAudit(){
        this.dialogVisible = true
      },
      //初始默认执行(重点)，返回日期格式YYYY-MM-DD HH:MM:SS
      getNowTime() {
            let dateTime = +new Date()+8*3600*1000
            const start = new Date(dateTime - 3600 * 1000 * 24 * 7)
                .toISOString()
                .replace('T', ' ')
                .split('.')[0]
                // .substring(0,10) //默认开始时间7天前
            const end = new Date(dateTime)
                .toISOString()
                .replace('T', ' ')
                .split('.')[0]
                // .substring(0,10)//默认结束时间当前时间
            console.log([start, end])
            return [start, end]
        },
      // 导出excel
      async hExportExcel() {
          this.loading = true
          let query = Object.assign({},this.listQuery)
          query.page = 1
          query.limit = 10000
            if(!query.workOrderNo){ delete query.workOrderNo }
            if(!query.deviceBarcode){ delete query.deviceBarcode }
            if(!query.technologyNo){ delete query.technologyNo }
            if(!query.processOrder){ delete query.processOrder }
            if(!query.processName){ delete query.processName }
            if(!query.isDelete){ delete query.isDelete }
            if(query.isDelete){
              query.isDelete = query.isDelete =='未删除'?'0':'1'
            }
            if(this.dateOptions) {
              if(this.dateOptions.length) {
                  query.startDate = this.dateOptions[0]
                  query.endDate = this.dateOptions[1]
              }
            }
          let arr = await findDeviceBarcodeCode(query)
          if(arr.code == '500') return
          if(arr.code != '1'){
            this.loading = false
            return this.$message.error(errmsg)
          }
          if(!arr.data.list.length){
            this.loading = false
            this.$message.error('暂无数据')
          }
          const { header, data } = this.transformDat(this.setSort(arr.data.list))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: 'ems条码过站', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        transformDat(res) {
          const mapInfo = {
            index: '序号',
            workCenter: '工作中心',
            sectionAbbreviation: '线体',
            clientNumber: '各户品号',
            scanProcessOrder: '工序编号',
            scanProcessName: '工序名称',
            scanOrderType: '工别',
            scanWorkOrderNo: '工单',
            deviceBarcode: '机柜条码',
            scanProduceNo: '品号',
            scanTime: '扫码时间',
            isDelete: '是否删除',
            checkPassEms: 'QC检验状态',
            checkPass: 'OBA检验状态',
            userName: '工作人员',
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = []
          newArr.forEach((item,index)=>{
            let obj = {
              index: 1 + index,
              workCenter: item.workCenter,
              sectionAbbreviation: item.sectionAbbreviation,
              clientNumber: item.clientNumber,
              scanProcessOrder: item.scanProcessOrder,
              scanProcessName: item.scanProcessName,
              scanOrderType: item.scanOrderType,
              scanWorkOrderNo: item.scanWorkOrderNo,
              deviceBarcode: item.deviceBarcode,
              scanProduceNo: item.scanProduceNo,
              scanTime: item.scanTime,
              isDelete: item.isDelete == 0 ? "未删除" : "已删除",
              checkPassEms: item.checkPassEms == 0 ? "未检查" : item.checkPassEms == 1 ? "合格" : item.checkPassEms == 2 ? "不合格":"",
              checkPass: item.checkPass == 0 ? "未检查" : item.checkPass == 1 ? "合格" : item.checkPass == 2 ? "不合格":"",
              userName: item.userName,
            }
            arr1.push(obj)
          })
          return arr1
        },
        async handleFilter() {
            this.listLoading = true
            let query = Object.assign({},this.listQuery)
            if(!query.workOrderNo){ delete query.workOrderNo }
            if(!query.deviceBarcode){ delete query.deviceBarcode }
            if(!query.technologyNo){ delete query.technologyNo }
            if(!query.processOrder){ delete query.processOrder }
            if(!query.processName){ delete query.processName }
            if(!query.isDelete){ delete query.isDelete }
            if(query.isDelete){
              query.isDelete = query.isDelete =='未删除'?'0':'1'
            }
            if(this.dateOptions) {
              if(this.dateOptions.length) {
                  query.startDate = this.dateOptions[0]
                  query.endDate = this.dateOptions[1]
              }
            }
            const {data} = await findDeviceBarcodeCode(query)
            this.tablelList = data.list
            this.total = data.count
            this.listLoading = false
        },
        getData() {
            this.listQuery.page = 1
            this.listQuery.limit = 20
            this.handleFilter()
        }, 
        handleSizeChange(val) {
            this.listQuery.limit = val
            this.handleFilter()
        },
        handleCurrentChange(val) {
            this.listQuery.page = val
            this.handleFilter()
        }
    },
      // 在生命周期函数调用"搜索"按钮绑定的函数，显示已有的数据
    mounted() {
        this.handleFilter()
  },
}
</script>

<style>

</style>